package com.cloudcc.boot.utils.util;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;

import jakarta.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class CRMAPI {

    private static String binding;

    public String getBinding() {
        return binding;
    }

    private static String CRMAPIUrl = "";
    private static String userName = "";
    private static String passWord = "";
    protected static String SUCCESS = "0";
    private static final Logger log = Logger.getLogger(CRMAPI.class);
    private CRMAPI(String binding) {
        this.binding = binding;
    }
    /**
     *
     * @throws IOException
     */
    public static String login(String url,String userName,String passWord) throws IOException {
        try {
            String result = sendPostRequest("url","serviceName=clogin&userName=" + userName + "&password=" + passWord);
            JSONObject json = JSONObject.fromObject(result);
            if (json.getBoolean("result")) {
                String binding = json.getString("binding");
                log.info(binding);
                return binding;
            } else {
                log.error("CRM API login失败：" + json.getString("returnInfo"));
                throw new IOException(json.getString("returnInfo"));
            }
        } catch (IOException ex) {
            log.error("CRM API 登陆失败：" + ex.getMessage());
            throw ex;
        }
    }

    public static JSONArray cquery(String ccAPI, String expression) throws IOException {
        String param = "serviceName=cquery&objectApiName=" + ccAPI + "&expressions=" + expression + "&binding="
                + binding;
        String result = sendPostRequest(param);
        JSONObject json = JSONObject.fromObject(result);
        if (json.getBoolean("result")) {
            return JSONArray.fromObject(json.getString("data"));
        } else {
            log.error("CRM API cquery失败：" + json.getString("returnInfo"));
            throw new IOException(json.getString("returnInfo"));
        }
    }

    public static JSONObject cqlQuery(String ccAPI, String expression) throws IOException {
        String param = "serviceName=cqlQuery&objectApiName=" + ccAPI + "&expressions=" + expression + "&binding="
                + binding;
        String result = sendPostRequest(param);
        JSONObject json = JSONObject.fromObject(result);
        if (json.getBoolean("result")) {
            return json;
        } else {
            log.error("CRM API cquery失败：" + json.getString("returnInfo"));
            throw new IOException(json.getString("returnInfo"));
        }
    }

    public static List<String> insert(String CCPAI, JSONArray jsonData) throws IOException {
        String param = "serviceName=insert&objectApiName=" + CCPAI + "&data="
                + URLEncoder.encode(jsonData.toString(), "utf8") + "&binding=" + binding;
        String result = sendPostRequest(param);
        JSONObject json = JSONObject.fromObject(result);
        log.info("新增");
        if (!json.getBoolean("result")) {
            log.error("CRM API INSERT失败：" + json.getString("returnInfo"));
            throw new IOException(json.getString("returnInfo"));
        }
        log.info("【http insert】returnData:" + json.getString("data"));

        JSONObject rtnData = JSONObject.fromObject(json.getString("data"));
        JSONArray idsJsonArray = rtnData.getJSONArray("ids");

        List<String> ids = new ArrayList<String>();
        for (int i = 0; i < idsJsonArray.size(); i++) {
            ids.add(idsJsonArray.getJSONObject(i).getString("id"));
        }
        return ids;
    }

    /**
     * 修改数据到crm
     *
     * @param CCPAI
     *            API名称
     * @param jsonData
     *            添加数据、json格式需要id即可
     * @return
     */
    public void update(String CCPAI, JSONArray jsonData) throws IOException {
        String param = "serviceName=update&objectApiName=" + CCPAI + "&data="
                + URLEncoder.encode(jsonData.toString(), "utf8") + "&binding=" + binding;
        String result = sendPostRequest(param);
        JSONObject json = JSONObject.fromObject(result);
        if (!json.getBoolean("result")) {
            log.error("CRM API UPDATE失败：" + json.getString("returnInfo"));
            throw new IOException(json.getString("returnInfo"));
        }
    }

    public void update(String CCPAI, JSONObject jsonData) throws IOException {
        JSONArray arrayforUpdate = new JSONArray();
        arrayforUpdate.add(jsonData);
        update(CCPAI, arrayforUpdate);
    }

    /**
     * 删除数据到crm
     *
     * @param CCPAI
     * @param id
     *            记录id
     * @throws IOException
     */
    public void delete(String CCPAI, String id) throws IOException {
        List<String> ids = new ArrayList<String>();
        ids.add(id);
        delete(CCPAI, ids);
    }

    public static void delete(String CCPAI, List<String> ids) throws IOException {
        JSONArray jsonIds = new JSONArray();
        for (String id : ids) {
            JSONObject jsonId = new JSONObject();
            jsonId.put("id", id);
            jsonIds.add(jsonId);
        }
        String param = "serviceName=delete&objectApiName=" + CCPAI + "&data=" + jsonIds.toString() + "&binding="
                + binding;
        String result = sendPostRequest(param);
        JSONObject json = JSONObject.fromObject(result);
        if (!json.getBoolean("result")) {
            log.error("CRM API DELETE失败：" + json.getString("returnInfo"));
            throw new IOException(json.getString("returnInfo"));
        }
    }

    // 发送html接口请求
    private static String sendPostRequest(String param) throws IOException {
        OutputStreamWriter out = null;
        BufferedReader br = null;
        try {
            java.net.URL url = new java.net.URL(CRMAPIUrl);
            java.net.HttpURLConnection con = (java.net.HttpURLConnection) url.openConnection();
            con.setDoOutput(true);
            con.setRequestMethod("POST"); // post 方式请求
            out = new OutputStreamWriter(con.getOutputStream(), "utf-8");
            out.write(param);
            out.flush();
            // 处理返回结果
            int respCode = con.getResponseCode();
            if (respCode == 200) { // 如果能正常返回
                InputStream is = con.getInputStream();
                br = new BufferedReader(new java.io.InputStreamReader(is, "utf-8"));
                String result = ""; // Json格式的调用返回结果
                String line;
                while ((line = br.readLine()) != null) {
                    result += line;
                }
                return result;
            } else { // 如果出现调用失败的情况
                log.error("POST 请求没有正常返回,response code:" + respCode);
                throw new IOException();
            }
        } finally {
            if (br != null) {
                br.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
    // 发送html接口请求
    public static String sendPostRequest(String sendUrl, String param) throws IOException {
        OutputStreamWriter out = null;
        BufferedReader br = null;
        try {
            java.net.URL url = new java.net.URL(sendUrl);
            java.net.HttpURLConnection con = (java.net.HttpURLConnection) url.openConnection();
            con.setDoOutput(true);
            con.setRequestMethod("POST"); // post 方式请求
            //con.setRequestProperty("Content-Type", "application/json");// 之前没设置参数格式...加上这句就好了
            out = new OutputStreamWriter(con.getOutputStream(), "utf-8");
            out.write(param);
            out.flush();
            // 处理返回结果
            int respCode = con.getResponseCode();
            if (respCode == 200) { // 如果能正常返回
                InputStream is = con.getInputStream();
                br = new BufferedReader(new java.io.InputStreamReader(is, "utf-8"));
                String result = ""; // Json格式的调用返回结果
                String line;
                while ((line = br.readLine()) != null) {
                    result += line;
                }
                return result;
            } else { // 如果出现调用失败的情况
                throw new IOException();
            }
        } finally {
            if (br != null) {
                br.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }

    public String renderError(HttpServletResponse response, String errorCode) {
        JSONObject result = new JSONObject();
        result.put("return", errorCode);
        return result.toString();
    }

    public String renderSuccess(HttpServletResponse response) {
        JSONObject result = new JSONObject();
        result.put("return", SUCCESS);
        return result.toString();
    }

    public String renderSuccess(HttpServletResponse response, String data) {
        JSONObject result = new JSONObject();
        result.put("return", SUCCESS);
        result.put("data", data);
        return result.toString();
    }

    private void render(HttpServletResponse response, String text) {
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Pragma", "No-cache");
        //response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        try {
            response.getWriter().write(text);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException ex) {
            log.error("[render error]", ex);
        }
    }

    public String isNull(String param) {
        return param == null ? "" : param;
    }

    /**
     * 将ISO-8859-1编码格式的字符串转码为UTF-8
     *
     * @param parameterValue
     * @return
     * @throws UnsupportedEncodingException
     */
    public String encodeParameters(String parameterValue)
            throws UnsupportedEncodingException {
        if (parameterValue != null && parameterValue.length() > 0) {
            byte[] iso = parameterValue.getBytes("ISO-8859-1");
            if (parameterValue.equals(new String(iso, "ISO-8859-1"))) {
                parameterValue = new String(iso, "UTF-8");
                return parameterValue;
            }
        }
        return parameterValue;
    }

}